<?php
namespace App;

use DB;

class DataTablesHelper {
    
   private static function buildWhere($db,$where){
         if(is_array($where)){
            $eq = $where["EQ"];
            //----EQ
            if(is_array($eq)){
                foreach($eq as $f => $fv){
                    if(empty($fv))continue;
                    $db = $db->where($f,"=",$fv);
                }
            }

            //----LIKE
            $like = $where["LIKE"];
            if(is_array($like)){
               foreach($like as $f => $fv){
                   if(empty($fv))continue;
                   $fv = "%$fv%";
                   $db = $db->where($f,"LIKE",$fv);
               }
            }
        }

        return $db;
    }
    
    static function getData($request,$param,$where){
        if(!is_array($param)){
            return;
        }

        $start = intval($request->input('start'));
        $len = intval($request->input('length'));
        $draw = intval($request->input('draw'));

        $total = DB::table($param["tableName"]);
        $total = DataTablesHelper::buildWhere($total,$where)->count();

        $list = DB::table($param["tableName"]);
        $list = DataTablesHelper::buildWhere($list,$where);
        $list = $list->skip($start)->take($len);

        if(is_array($param["orderCoumns"])){
            foreach($param["orderCoumns"] as $f=>$fv)
                $list = $list->orderBy($f,$fv);
        }
        
        $list = $list->get();

        $returnData = array(
            "draw" => $draw,
            "recordsTotal" => $total,
            "recordsFiltered" => $total,
            "data" => $list
        );

        return json_encode($returnData);
    }

}

?>